<script setup lang="ts">
import EZUIKit from 'ezuikit-js'
import { YsVideo } from '@yk/components/ys-video/type'
import BtnLineRec from '@yk/components/ys-video/components/BtnLineRec.vue'
import { EZUIKitPlayerOptions } from './@type'
import { VideoDTO } from '@/api/entity/video'

const props = withDefaults(defineProps<{
  ysVideo: YsVideo | VideoDTO,
  autoPlay?: boolean,
  template?: EZUIKitPlayerOptions['template'],
  themeData?: EZUIKitPlayerOptions['themeData'],
}>(), {
  template: 'pcLive',
  autoPlay: true
})

const playerId = shallowRef()
const videoRef = shallowRef<HTMLDivElement>()
const player = shallowRef<EZUIKit.EZUIKitPlayer>()

onMounted(() => {
  playerId.value = 'yk-ys-video_' + Date.now() + ~~(Math.random() * 10000)
  initYsVideo()
  autoPlayHandle()
})

onBeforeUnmount(() => {
  player.value && player.value.stop()
  document.getElementById('audioleft').remove()
  document.getElementById('audioright').remove()
})

// region TODO 初始化
const _ysVideo = ref<YsVideo>()
function initYsVideo () {
  if ((props.ysVideo as YsVideo).deviceSerial) {
    _ysVideo.value = props.ysVideo as YsVideo
  } else {
    const { name, number, token, passage, code } = props.ysVideo as VideoDTO
    _ysVideo.value = new YsVideo({
      // 视频名称
      videoName: name,
      // 访问令牌
      accessToken: token,
      // 设备序列号
      deviceSerial: number,
      // 通道
      channelNo: Number(passage),
      // 验证码
      validCode: code
    })
  }
}
function loadVideo () {
  player.value = new EZUIKit.EZUIKitPlayer({
    id: playerId.value, // 视频容器ID
    template: props.themeData ? undefined : props.template,
    url: getPlayerUrl(),
    height: 1, // 利用ResizeObserver重置高度，初始化的高度有一瞬间比较高
    accessToken: _ysVideo.value.accessToken,
    themeData: props.themeData
  })
  addResizeObserver()
}
// endregion

// region TODO 首次播放
const showPlayMask = shallowRef(true)
function autoPlayHandle () {
  if (props.autoPlay) firstPlay()
}

function firstPlay () {
  showPlayMask.value = false
  nextTick(loadVideo)
}
// endregion

// region TODO 工具函数
// 获取容器大小
function getContainerRect () {
  return videoRef.value.getBoundingClientRect()
}

// 获取播放地址
function getPlayerUrl () {
  const { validCode, channelNo, deviceSerial } = _ysVideo.value
  // 前缀协议
  let result = 'ezopen://'
  // 如果有验证码拼接验证码
  if (validCode) result += validCode + '@'
  // 拼接设备序列号和通道
  result += 'open.ys7.com/' + deviceSerial + '/' + channelNo + '.'
  // 拼接直播模式还是回放模式
  result += ['mobileRec', 'pcRec'].includes(props.template) ? 'rec' : 'live'
  return result
}
// endregion

// region TODO 监听容器大小变化
let observer: ResizeObserver = null
function addResizeObserver () {
  observer = new ResizeObserver(() => {
    const { width, height } = getContainerRect()
    player.value.reSize(width, height)
  })
  observer.observe(videoRef.value)
}
function removeResizeObserver () {
  if (observer) {
    observer.unobserve(videoRef.value)
    observer.disconnect()
  }
}
onBeforeUnmount(() => {
  removeResizeObserver()
})
// endregion

defineExpose({ getPlayer: () => player.value })
</script>

<template>
  <div class="overflow-hidden yk-ys-video">
    <div ref="videoRef" class="wh-100 position-relative">
      <div :id="playerId" class="wh-100" />
      <btn-line-rec v-if="player" :player="player" class="position-absolute" style="top: 0;right:64px;" />
      <div v-if="showPlayMask" class="position-absolute wh-100 play-mask d-flex-center" :style="{ backgroundImage: `url(${_ysVideo?.image})` }">
        <div class="position-absolute header">
          <div class="title-box overflow-ellipsis color-white">{{ _ysVideo?.videoName }}</div>
        </div>
        <img src="./images/btn-play.png" class="cursor-pointer" alt="" @click="firstPlay">
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.yk-ys-video::v-deep(.header-controls) {
    div:nth-child(2) {
      .theme-icon-item {
        width: 32px !important;
        display: flex;
        justify-content: center;
        align-items: center;
        padding-top: 6px;
        svg {
          height: 48px !important;
          width: 48px !important;
        }
      }
      .theme-icon-item:last-child{
        padding-left: 16px;
      }
    }
}
.play-mask {
  background-color: #626365;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  top: 0;
  left: 0;
  .header {
    height: 20%;inset: 0 auto auto 0;
    min-height: 48px;
    background: linear-gradient(to bottom, #00000088 0, #00000066 30%, #00000033 50%, #00000000 100%);
    padding: 10px 8px;
    width: 100%;
    .title-box {
      max-width: 50%;
      height: 48px;
    }
  }
}
</style>
